package com.syf.kit.soa.core.send.protocol.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.util.AttributeKey;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class LongTcpConnectionFactory implements PooledObjectFactory<LongTcpConnection> {
    private String host;

    private Integer port;

    private Bootstrap bootstrap;

    /**
     * 连接建立的超时时间，单位：毫秒
     */
    private Long connTimeout;

    private AttributeKey<Boolean> USABLE_ATTR_KEY;

    public LongTcpConnectionFactory(String host, int port, Bootstrap bootstrap, Long connTimeout, AttributeKey<Boolean> USABLE_ATTR_KEY) {
        this.host = host;
        this.port = port;
        this.bootstrap = bootstrap;
        this.connTimeout = connTimeout;
        this.USABLE_ATTR_KEY = USABLE_ATTR_KEY;
    }

    /**
     * 激活对象，当从池中获取一个对象时，如果该对象之前没有被激活过，会调用此方法。这个方法可以用来在对象被使用前进行一些初始化操作
     */
    @Override
    public void activateObject(PooledObject<LongTcpConnection> pooledObject) throws Exception {

    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<LongTcpConnection> pooledObject) throws Exception {
        pooledObject.getObject().close();
    }

    /**
     * 创建对象
     */
    @Override
    public PooledObject<LongTcpConnection> makeObject() throws Exception {
        LongTcpConnection longTcpConnection = new LongTcpConnection(bootstrap, connTimeout, USABLE_ATTR_KEY);
        longTcpConnection.connect(host, port);
        return new DefaultPooledObject<>(longTcpConnection);
    }

    /**
     * 对象失活，当对象不再使用时，会被归还到池中，此时会调用此方法。这个方法可以用来在对象被回收前进行一些清理操作。
     */
    @Override
    public void passivateObject(PooledObject<LongTcpConnection> pooledObject) throws Exception {

    }

    /**
     * 验证对象有效性
     */
    @Override
    public boolean validateObject(PooledObject<LongTcpConnection> pooledObject) {
        return pooledObject.getObject().isUsable();
    }
}
